package com.naiterui.ehp.bs.patient.controller.openapi;

import com.naiterui.common.redis.RedisUtil;
import com.naiterui.ehp.bp.support.exception.PublicService;
import com.naiterui.ehp.bp.support.exception.ResponseVO;
import com.naiterui.ehp.bp.utils.encypt.MD5;
import com.naiterui.ehp.bs.patient.constants.PatientJumperEnum;
import com.naiterui.ehp.bs.patient.service.IPatientService;
import com.naiterui.ehp.bs.patient.service.ISubscribeNoticeService;
import com.naiterui.ehp.bs.patient.utils.exception.PatientBusinessException;
import com.naiterui.ehp.bs.wechat.service.IWebAuthorizeApiService;
import com.naiterui.ehp.bs.wechat.utils.WeChatApiUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author gaoliangliang
 * @date 2019-07-09 11:50
 * @since 1.0.0
 */
@Slf4j
@RestController
@RequestMapping("ap/openapi/patient")
public class WxPatientController {

    private static final int DEFAULT_CODE_EXPIRE = 15;

    private IWebAuthorizeApiService webAuthorizeApiService;
    private IPatientService patientService;
    private ISubscribeNoticeService subscribeNoticeService;

    public WxPatientController(IWebAuthorizeApiService webAuthorizeApiService, IPatientService patientService, ISubscribeNoticeService SubscribeNoticeService) {
        this.webAuthorizeApiService = webAuthorizeApiService;
        this.patientService = patientService;
        this.subscribeNoticeService = SubscribeNoticeService;
    }

    @RequestMapping
    public void wechatPatient(HttpServletResponse response, String code, String state) throws IOException {

        String openId = webAuthorizeApiService.codeForOpenId(code);
        String[] params = state.split(WeChatApiUtil.WX_DEFAULT_PARAM_SPLIT);
        String scene = params.length > 0 ? params[0] : StringUtils.EMPTY;
        String param = params.length > 1 ? params[1] : null;
        if (openId != null) {
            String md5Code = MD5.md5(code);
            RedisUtil.valueOps().setEx(md5Code, openId, DEFAULT_CODE_EXPIRE);
            String aimUrl = PatientJumperEnum.getByScene(scene).encodeCodeUrl(param, md5Code);
            log.info("重定向跳转前端页面地址 {}", aimUrl);
            response.sendRedirect(aimUrl);
        }

        //TODO 2019-07-11 16:03 高亮亮 H5授权失败通用页面
    }

    @GetMapping("code2token")
    public ResponseVO<String> code2token(String code) throws PatientBusinessException {
        String token = patientService.updateCode2token(code);
        return PublicService.returnResponseVO(token);
    }

}
